﻿using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace KjxingTools
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 绑定的数据
        /// </summary>
        ObservableCollection<PortUserInfo> _Items = new ObservableCollection<PortUserInfo>();

        public MainWindow()
        {
            InitializeComponent();
            t_port.Focus();
            d_port.ItemsSource = _Items;
        }

        /// <summary>
        /// 限制只能输入数字
        /// </summary>
        /// <param name="e"></param>
        public void limitnumber(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9]+");
            e.Handled = re.IsMatch(e.Text);
        }

        private void btn_search_Click(object sender, RoutedEventArgs e)
        {
            int port = IntegerType.FromString(t_port.Text);
            var proc = WhoUsePort.NetStatus(port, (bool)c_isLocal.IsChecked);
            _Items.Clear();
            foreach (var p in proc)
            {
                _Items.Add(p);
            }
        }

        private void t_port_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
            {
                btn_search_Click(sender, e);
            }
        }

        private void btn_kill_Click(object sender, RoutedEventArgs e)
        {
            var SelectedRow = (PortUserInfo)d_port.SelectedItem;
            string msg = $"确认结束进程[{SelectedRow.ProcessName}]:[pid={SelectedRow.Pid}]吗?\r\n请确认结束进程的不会带来严重后果.";
            var dr = MessageBox.Show(msg, "警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
            if (dr == MessageBoxResult.OK)
            {
                SelectedRow.Process.Kill();
                btn_search_Click(sender, e);
            }
        }
    }
}
